<template>
  <div class="lawyer-case-overview">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">
            <i class="fas fa-user-tie mr-3"></i>律师案件管理
          </h1>
          <p class="page-description">按律师维度查看和管理案件信息，支持案件状态筛选和钻取查看</p>
        </div>
        <div class="header-actions">
          <el-button @click="refreshData">
            <i class="fas fa-sync mr-2"></i>刷新数据
          </el-button>
          <el-button @click="exportLawyerData">
            <i class="fas fa-file-export mr-2"></i>导出数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon bg-blue-100">
          <i class="fas fa-user-tie text-blue-600"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.totalLawyers }}</div>
          <div class="stat-label">总律师数</div>
          <div class="stat-change positive">
            <i class="fas fa-arrow-up"></i>
            本月活跃 {{ statistics.activeLawyers }}
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon bg-green-100">
          <i class="fas fa-briefcase text-green-600"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.totalCases }}</div>
          <div class="stat-label">总案件数</div>
          <div class="stat-change positive">
            <i class="fas fa-arrow-up"></i>
            平均每人 {{ avgCasesPerLawyer }} 件
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon bg-orange-100">
          <i class="fas fa-clock text-orange-600"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.activeCases }}</div>
          <div class="stat-label">在办案件</div>
          <div class="stat-change neutral">
            <i class="fas fa-minus"></i>
            处理中案件
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon bg-purple-100">
          <i class="fas fa-check-circle text-purple-600"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.completedCases }}</div>
          <div class="stat-label">已结案件</div>
          <div class="stat-change positive">
            <i class="fas fa-arrow-up"></i>
            结案率 {{ completionRate }}%
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <div class="filter-left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索律师姓名、案件编号..."
          prefix-icon="el-icon-search"
          class="search-input"
          @input="handleSearch"
        />
        
        <el-select v-model="filters.caseStatus" placeholder="案件状态" class="filter-select">
          <el-option label="全部状态" value="" />
          <el-option label="在办案件" value="active" />
          <el-option label="已结案件" value="completed" />
          <el-option label="待分配" value="pending" />
        </el-select>

        <el-select v-model="filters.caseType" placeholder="案件类型" class="filter-select">
          <el-option label="全部类型" value="" />
          <el-option label="交通事故" value="traffic" />
          <el-option label="人身损害" value="personal" />
          <el-option label="意外险" value="accident" />
          <el-option label="工伤职伤" value="work" />
        </el-select>

        <el-select v-model="filters.department" placeholder="所属部门" class="filter-select">
          <el-option label="全部部门" value="" />
          <el-option label="律师部" value="lawyer" />
          <el-option label="高级律师组" value="senior" />
          <el-option label="专业律师组" value="professional" />
        </el-select>
      </div>

      <div class="filter-right">
        <el-button @click="resetFilters">
          <i class="fas fa-undo mr-1"></i>重置
        </el-button>
        <el-button type="primary" @click="applyFilters">
          <i class="fas fa-filter mr-1"></i>应用筛选
        </el-button>
      </div>
    </div>

    <!-- 律师案件列表 -->
    <div class="lawyer-list-container">
      <el-table
        :data="filteredLawyers"
        stripe
        class="lawyer-table"
        v-loading="loading"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="name" label="律师姓名" width="120" sortable>
          <template #default="{ row }">
            <div class="lawyer-info">
              <el-avatar :size="32" :src="row.avatar" class="mr-2">
                {{ row.name.charAt(0) }}
              </el-avatar>
              <div>
                <div class="lawyer-name">{{ row.name }}</div>
                <div class="lawyer-title">{{ row.title }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="department" label="所属部门" width="120">
          <template #default="{ row }">
            <span class="department-badge" :class="getDepartmentClass(row.department)">
              {{ getDepartmentText(row.department) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="totalCases" label="总案件数" width="100" sortable>
          <template #default="{ row }">
            <el-button type="text" @click="viewLawyerCases(row, 'all')" class="case-count-link">
              {{ row.totalCases }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column prop="activeCases" label="在办案件" width="100" sortable>
          <template #default="{ row }">
            <el-button type="text" @click="viewLawyerCases(row, 'active')" class="case-count-link active">
              {{ row.activeCases }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column prop="completedCases" label="已结案件" width="100" sortable>
          <template #default="{ row }">
            <el-button type="text" @click="viewLawyerCases(row, 'completed')" class="case-count-link completed">
              {{ row.completedCases }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column prop="pendingCases" label="待分配案件" width="120" sortable>
          <template #default="{ row }">
            <el-button type="text" @click="viewLawyerCases(row, 'pending')" class="case-count-link pending">
              {{ row.pendingCases }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="案件类型分布" width="200">
          <template #default="{ row }">
            <div class="case-type-distribution">
              <div v-for="type in row.caseTypeDistribution" :key="type.type" class="type-item">
                <el-tag :type="getCaseTypeColor(type.type)" size="small">
                  {{ getCaseTypeText(type.type) }}: {{ type.count }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="completionRate" label="结案率" width="100" sortable>
          <template #default="{ row }">
            <div class="completion-rate">
              <el-progress 
                :percentage="row.completionRate" 
                :color="getCompletionRateColor(row.completionRate)"
                :stroke-width="6"
                text-inside
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="avgProcessingDays" label="平均处理时长" width="120" sortable>
          <template #default="{ row }">
            <span class="processing-days">{{ row.avgProcessingDays }}天</span>
          </template>
        </el-table-column>

        <el-table-column prop="lastActiveDate" label="最近活动" width="120" sortable>
          <template #default="{ row }">
            <span class="last-active">{{ formatDate(row.lastActiveDate) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="text" size="small" @click="viewLawyerDetail(row)">
                <i class="fas fa-eye mr-1"></i>详情
              </el-button>
              <el-button type="text" size="small" @click="viewLawyerCases(row, 'all')">
                <i class="fas fa-list mr-1"></i>全部案件
              </el-button>
              <el-dropdown @command="handleMoreAction" trigger="click">
                <el-button type="text" size="small">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{action: 'assign', lawyer: row}">
                      <i class="fas fa-plus mr-2"></i>分配案件
                    </el-dropdown-item>
                    <el-dropdown-item :command="{action: 'performance', lawyer: row}">
                      <i class="fas fa-chart-line mr-2"></i>绩效分析
                    </el-dropdown-item>
                    <el-dropdown-item :command="{action: 'workload', lawyer: row}">
                      <i class="fas fa-balance-scale mr-2"></i>工作量调整
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'

export default {
  name: 'LawyerCaseOverview',
  setup() {
    const router = useRouter()
    
    // 响应式数据
    const loading = ref(false)
    const searchQuery = ref('')

    // 筛选条件
    const filters = reactive({
      caseStatus: '',
      caseType: '',
      department: ''
    })

    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 20,
      total: 0
    })

    // 统计数据
    const statistics = reactive({
      totalLawyers: 0,
      activeLawyers: 0,
      totalCases: 0,
      activeCases: 0,
      completedCases: 0
    })

    // 律师数据
    const lawyers = ref([])

    // 计算属性
    const avgCasesPerLawyer = computed(() => {
      return statistics.totalLawyers > 0 ? 
        Math.round(statistics.totalCases / statistics.totalLawyers) : 0
    })

    const completionRate = computed(() => {
      return statistics.totalCases > 0 ? 
        Math.round((statistics.completedCases / statistics.totalCases) * 100) : 0
    })

    // 过滤后的律师列表
    const filteredLawyers = computed(() => {
      let result = lawyers.value

      // 搜索筛选
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(lawyer => 
          lawyer.name.toLowerCase().includes(query) ||
          lawyer.cases.some(case_ => 
            case_.caseNumber.toLowerCase().includes(query)
          )
        )
      }

      // 案件状态筛选
      if (filters.caseStatus) {
        if (filters.caseStatus === 'active') {
          result = result.filter(lawyer => lawyer.activeCases > 0)
        } else if (filters.caseStatus === 'completed') {
          result = result.filter(lawyer => lawyer.completedCases > 0)
        } else if (filters.caseStatus === 'pending') {
          result = result.filter(lawyer => lawyer.pendingCases > 0)
        }
      }

      // 案件类型筛选
      if (filters.caseType) {
        result = result.filter(lawyer => 
          lawyer.caseTypeDistribution.some(type => type.type === filters.caseType)
        )
      }

      // 部门筛选
      if (filters.department) {
        result = result.filter(lawyer => lawyer.department === filters.department)
      }

      return result
    })

    // 初始化模拟数据
    const initData = () => {
      lawyers.value = [
        {
          id: 1,
          name: '李卫民',
          title: '高级律师',
          department: 'senior',
          avatar: '/avatars/lawyer1.jpg',
          totalCases: 45,
          activeCases: 12,
          completedCases: 30,
          pendingCases: 3,
          completionRate: 67,
          avgProcessingDays: 25,
          lastActiveDate: '2024-02-16',
          caseTypeDistribution: [
            { type: 'traffic', count: 20 },
            { type: 'personal', count: 15 },
            { type: 'work', count: 10 }
          ],
          cases: [] // 案件列表
        },
        {
          id: 2,
          name: '张华',
          title: '专业律师',
          department: 'professional',
          avatar: '/avatars/lawyer2.jpg',
          totalCases: 38,
          activeCases: 15,
          completedCases: 20,
          pendingCases: 3,
          completionRate: 53,
          avgProcessingDays: 30,
          lastActiveDate: '2024-02-15',
          caseTypeDistribution: [
            { type: 'traffic', count: 18 },
            { type: 'accident', count: 12 },
            { type: 'personal', count: 8 }
          ],
          cases: []
        },
        {
          id: 3,
          name: '王建国',
          title: '资深律师',
          department: 'senior',
          avatar: '/avatars/lawyer3.jpg',
          totalCases: 52,
          activeCases: 8,
          completedCases: 42,
          pendingCases: 2,
          completionRate: 81,
          avgProcessingDays: 20,
          lastActiveDate: '2024-02-16',
          caseTypeDistribution: [
            { type: 'traffic', count: 25 },
            { type: 'personal', count: 15 },
            { type: 'work', count: 12 }
          ],
          cases: []
        },
        {
          id: 4,
          name: '赵律师',
          title: '律师',
          department: 'lawyer',
          avatar: '/avatars/lawyer4.jpg',
          totalCases: 28,
          activeCases: 10,
          completedCases: 15,
          pendingCases: 3,
          completionRate: 54,
          avgProcessingDays: 35,
          lastActiveDate: '2024-02-14',
          caseTypeDistribution: [
            { type: 'work', count: 15 },
            { type: 'accident', count: 8 },
            { type: 'traffic', count: 5 }
          ],
          cases: []
        }
      ]

      updateStatistics()
    }

    // 更新统计数据
    const updateStatistics = () => {
      const total = lawyers.value.length
      const active = lawyers.value.filter(l => l.activeCases > 0).length
      const totalCases = lawyers.value.reduce((sum, l) => sum + l.totalCases, 0)
      const activeCases = lawyers.value.reduce((sum, l) => sum + l.activeCases, 0)
      const completedCases = lawyers.value.reduce((sum, l) => sum + l.completedCases, 0)
      
      statistics.totalLawyers = total
      statistics.activeLawyers = active
      statistics.totalCases = totalCases
      statistics.activeCases = activeCases
      statistics.completedCases = completedCases
      
      pagination.total = total
    }

    // 工具方法
    const getDepartmentClass = (department) => {
      const classMap = {
        lawyer: 'dept-lawyer',
        senior: 'dept-senior',
        professional: 'dept-professional'
      }
      return classMap[department] || 'dept-default'
    }

    const getDepartmentText = (department) => {
      const textMap = {
        lawyer: '律师部',
        senior: '高级律师组',
        professional: '专业律师组'
      }
      return textMap[department] || '未分配'
    }

    const getCaseTypeColor = (type) => {
      const colorMap = {
        traffic: 'primary',
        personal: 'success',
        accident: 'warning',
        work: 'danger'
      }
      return colorMap[type] || 'info'
    }

    const getCaseTypeText = (type) => {
      const textMap = {
        traffic: '交通事故',
        personal: '人身损害',
        accident: '意外险',
        work: '工伤职伤'
      }
      return textMap[type] || '其他'
    }

    const getCompletionRateColor = (rate) => {
      if (rate >= 80) return '#38a169'
      if (rate >= 60) return '#ed8936'
      return '#f56565'
    }

    const formatDate = (date) => {
      return dayjs(date).format('MM-DD')
    }

    // 事件处理方法
    const handleSearch = () => {
      pagination.currentPage = 1
    }

    const resetFilters = () => {
      searchQuery.value = ''
      filters.caseStatus = ''
      filters.caseType = ''
      filters.department = ''
      pagination.currentPage = 1
    }

    const applyFilters = () => {
      pagination.currentPage = 1
      ElMessage.success('筛选条件已应用')
    }

    const handleSortChange = ({ prop, order }) => {
      ElMessage.info(`按 ${prop} ${order === 'ascending' ? '升序' : '降序'} 排序`)
    }

    const handleSizeChange = (size) => {
      pagination.pageSize = size
      pagination.currentPage = 1
    }

    const handleCurrentChange = (page) => {
      pagination.currentPage = page
    }

    const refreshData = () => {
      loading.value = true
      setTimeout(() => {
        initData()
        loading.value = false
        ElMessage.success('数据已刷新')
      }, 1000)
    }

    const exportLawyerData = () => {
      ElMessage.success('律师数据导出功能开发中...')
    }

    // 查看律师案件列表
    const viewLawyerCases = (lawyer, status) => {
      // 跳转到律师案件详情页，传递律师ID和状态筛选
      router.push({
        name: 'AdminLawyerCaseDetail',
        params: { lawyerId: lawyer.id },
        query: { status, lawyerName: lawyer.name }
      })
    }

    const viewLawyerDetail = (lawyer) => {
      ElMessage.info(`查看律师详情: ${lawyer.name}`)
    }

    const handleMoreAction = ({ action, lawyer }) => {
      switch (action) {
        case 'assign':
          ElMessage.info(`为 ${lawyer.name} 分配案件`)
          break
        case 'performance':
          ElMessage.info(`查看 ${lawyer.name} 绩效分析`)
          break
        case 'workload':
          ElMessage.info(`调整 ${lawyer.name} 工作量`)
          break
      }
    }

    // 生命周期
    onMounted(() => {
      initData()
    })

    return {
      loading,
      searchQuery,
      filters,
      pagination,
      statistics,
      lawyers,
      filteredLawyers,
      avgCasesPerLawyer,
      completionRate,
      getDepartmentClass,
      getDepartmentText,
      getCaseTypeColor,
      getCaseTypeText,
      getCompletionRateColor,
      formatDate,
      handleSearch,
      resetFilters,
      applyFilters,
      handleSortChange,
      handleSizeChange,
      handleCurrentChange,
      refreshData,
      exportLawyerData,
      viewLawyerCases,
      viewLawyerDetail,
      handleMoreAction
    }
  }
}
</script>

<style scoped>
.lawyer-case-overview {
  padding: 24px;
  background-color: #f8fafc;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #1a202c;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
}

.page-description {
  color: #718096;
  margin: 0;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #1a202c;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  color: #718096;
  font-size: 14px;
  margin-bottom: 4px;
}

.stat-change {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-change.positive {
  color: #38a169;
}

.stat-change.neutral {
  color: #718096;
}

/* 筛选工具栏 */
.filter-toolbar {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-left {
  display: flex;
  gap: 12px;
  flex: 1;
  align-items: center;
}

.search-input {
  width: 250px;
}

.filter-select {
  width: 150px;
}

.filter-right {
  display: flex;
  gap: 8px;
}

/* 律师列表 */
.lawyer-list-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.lawyer-table {
  width: 100%;
}

.lawyer-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.lawyer-name {
  font-weight: 600;
  color: #1a202c;
  font-size: 14px;
}

.lawyer-title {
  font-size: 12px;
  color: #718096;
}

.department-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.dept-lawyer {
  background: #bee3f8;
  color: #2c5aa0;
}

.dept-senior {
  background: #fbb6ce;
  color: #97266d;
}

.dept-professional {
  background: #c6f6d5;
  color: #276749;
}

.dept-default {
  background: #e2e8f0;
  color: #4a5568;
}

.case-count-link {
  color: #3182ce;
  font-weight: 600;
  font-size: 16px;
}

.case-count-link.active {
  color: #ed8936;
}

.case-count-link.completed {
  color: #38a169;
}

.case-count-link.pending {
  color: #e53e3e;
}

.case-type-distribution {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.completion-rate {
  width: 100%;
}

.processing-days {
  font-weight: 500;
  color: #1a202c;
}

.last-active {
  font-size: 12px;
  color: #718096;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #e2e8f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .lawyer-case-overview {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-toolbar {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .filter-left {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
}
</style>
